package com.zoe.app.mybatisconfig;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;

/**
 * @author Zoe.Zhang
 * @date 2021/10/16
 * @description
 */
@Configuration
@MapperScan(basePackages = {"com.**.mappermaster"}, sqlSessionFactoryRef = "sqlSessionFactoryMaster", sqlSessionTemplateRef = "sqlSessionTemplateMaster")
public class MyBatisConfigMaster {
    private static final Logger log = LoggerFactory.getLogger(MyBatisConfigMaster.class);
    @Autowired
    @Qualifier(value = "master")
    private DataSource dataSource;

    @Bean
    SqlSessionFactory sqlSessionFactoryMaster() throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mappermaster/*.xml"));
        sqlSessionFactoryBean.setTypeAliasesPackage("com.zoe.app");
        log.info("主数据被加载");
        return sqlSessionFactoryBean.getObject();
    }

    @Bean
    SqlSessionTemplate sqlSessionTemplateMaster() throws Exception {
        return new SqlSessionTemplate(sqlSessionFactoryMaster());
    }
}
